<?
function GetAll($User_id)
{
	$conn = getConnection();
		echo 'called2';

	$sql = '
		SELECT CM.id, U.FirstName, U.LastName, L.Name, CM.Value
		FROM 2011_ContactMethods CM
			Join 2011_Lookups L ON CM.Lookup_id = L.id
			Join 2011_Users U ON CM.User_id=U.id
		';
	if(isset($User_id))
	{
		$sql .= " WHERE User_id=$User_id ";
	}
	echo $sql;
	return $conn->query($sql);
}
function Get($id)
{
	$conn = getConnection();
	$result = $conn->query("SELECT * FROM 2011_ContactMethods WHERE id=$id");
	$rs = $result->fetch_assoc();
	$conn->close();
	return $rs;
}
function Blank()
{
	return array();
}
function Save(&$rs)
{
	$conn = getConnection();
	$rs_old = $rs;
	$rs = EscapeAll($conn, $rs);
	if(isset($rs['id']))	// Editing
	{
		$sql = 	"UPDATE 2011_ContactMethods SET "
		.		" created_at='$rs[created_at]',"
		.		" updated_at='$rs[updated_at]',"
		.		" Lookup_id=$rs[Lookup_id],"
		.		" User_id=$rs[User_id],"
		.		" `Value`='$rs[Value]'"
		.		" WHERE id=$rs[id]"
		;
	}else{					// Adding
		$sql = 	"INSERT INTO 2011_ContactMethods (created_at, updated_at, Lookup_id, User_id, `Value`) "
		.		"Values ('$rs[created_at]', '$rs[updated_at]', $rs[Lookup_id], $rs[User_id], '$rs[Value]')";
	}
	$rs = $rs_old;
	//echo  $sql;
	$result = $conn->query($sql);
	$error = $conn->error;
	if(!isset($rs['id']))
	{
		$rs['id'] = $conn->insert_id;
	}
	$conn->close();
	if($error)
		return array('Server Error' => $error);
	else
		return null;
}
function Delete($id)
{
	$conn = getConnection();
	$conn->query("DELETE FROM 2011_ContactMethods WHERE id=$id");
	$error = $conn->error;
	$conn->close();
	if($error)
		return array('Server Error' => $error);
	else
		return null;
}
function Validate($rs)
{
	$errors = array();
	if( $rs['created_at'] == '')
		$errors['created_at'] = 'Create At can not be empty';
	if( !is_numeric($rs['Lookup_id']))
		$errors['Lookup_id'] = 'Lookup_id must be a number';
	if( $rs['Lookup_id'] == '')
		$errors['Lookup_id'] = 'Lookup_id is required';
	if( $rs['Lookup_id']==7 && !strpos($rs['Value'], '@') )
		$errors['Value'] = 'value must be a valid email address';
	if(count($errors) == 0)
		return null;
	return $errors;
}
function EscapeAll($conn, $rs)
{
	$ret = array();
	foreach($rs as $key => $value)
	{
		$ret[$key] = mysqli_real_escape_string($conn, $value);
	}
	return $ret;
}



